package org.garbagecan.quartzstudy.cron;

import java.util.TimeZone;

import org.quartz.Calendar;
import org.quartz.impl.calendar.BaseCalendar;

public class MultiRangeCalendar extends BaseCalendar {

	private static final long serialVersionUID = 5322491181588197693L;

	private TimeZone timeZone;
	private long[] startTimeStamps;
	private long[] endTimeStamps;

	public MultiRangeCalendar(long[] startTimeStamps, long[] endTimeStamps) {
		this(null, startTimeStamps, endTimeStamps, null);
	}

	public MultiRangeCalendar(Calendar baseCalendar, long[] startTimeStamps,
			long[] endTimeStamps) {
		this(baseCalendar, startTimeStamps, endTimeStamps, null);
	}

	public MultiRangeCalendar(long[] startTimeStamps, long[] endTimeStamps,
			TimeZone timeZone) {
		this(null, startTimeStamps, endTimeStamps, timeZone);
	}

	public MultiRangeCalendar(Calendar baseCalendar, long[] startTimeStamps,
			long[] endTimeStamps, TimeZone timeZone) {
		super(baseCalendar);
		if (startTimeStamps.length != endTimeStamps.length) {
			throw new IllegalArgumentException("Array length does not match!");
		}
		this.setTimeZone(timeZone);
		this.startTimeStamps = startTimeStamps;
		this.endTimeStamps = endTimeStamps;
	}

	public void setBaseCalendar(Calendar baseCalendar) {
		super.setBaseCalendar(baseCalendar);
	}

	public boolean isTimeIncluded(long timeStamp) {
		if ((getBaseCalendar() != null)
				&& (getBaseCalendar().isTimeIncluded(timeStamp) == false)) {
			return false;
		}
		for (int i = 0; i < startTimeStamps.length; i++) {
			if (timeStamp >= startTimeStamps[i]
					&& timeStamp <= endTimeStamps[i]) {
				return false;
			}
		}
		return true;
	}

	public long getNextIncludedTime(long timeStamp) {
		for (int i = 0; i < startTimeStamps.length; i++) {
			if (timeStamp >= startTimeStamps[i]
					&& timeStamp <= endTimeStamps[i]) {
				return timeStamp;
			}
		}
		return 0;
	}

	public TimeZone getTimeZone() {
		return timeZone;
	}

	public void setTimeZone(TimeZone timeZone) {
		this.timeZone = timeZone;
	}
}
